package cn.edu.njnu.opengmpback.Config;

import cn.edu.njnu.opengmpback.common.utils.RestTemplateUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MyInterceptor implements HandlerInterceptor{

    String userServerIpAndPort;
    public MyInterceptor(String userServerIpAndPort) {
        this.userServerIpAndPort = userServerIpAndPort;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws IOException {
        String token = request.getHeader("Authorization");
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) return true;
        if (request.getServletPath().equals("/user") && request.getMethod().equals("POST")) return true;
        if(token == null || token.equals("")){
            ServletOutputStream writer = response.getOutputStream();
            writer.print("Offline");
            writer.flush();
            writer.close();
            return false;
        }
        String StateUrl = "http://" + userServerIpAndPort + "/auth/userInfo";
        RestTemplateUtil httpUtil = new RestTemplateUtil();
        JSONObject updateResultJson = httpUtil.getRequestToServer(StateUrl, token).getBody();
        if (updateResultJson.getInteger("code") != 0) {
            ServletOutputStream writer = response.getOutputStream();
            writer.print("Offline");
            writer.flush();
            writer.close();
            return false;
        }
        return true;
    }

}
